package com.education.wisdom.controller.app;

import com.alibaba.fastjson.JSON;
import com.education.common.pojo.TStudent;
import com.education.wisdom.feign.WelcoFeign;
import com.education.wisdom.pojo.*;
import com.education.wisdom.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.education.common.core.BaseController.writeJSON;

/**
 * 试卷表
 *
 * @date 2021-03-04 15:45:18
 */
@RestController
@RequestMapping("/wisdom/apporderpaper")
public class AppOrderPaperController {

    @Autowired
    private OrderPaperService orderPaperService;

    @Autowired
    private OrderPaperQuestionService orderPaperQuestionService;

    @Autowired
    private OrderQuestionService orderQuestionService;

    @Autowired
    private OrderAnswerService orderAnswerService;

    @Autowired
    private OrderUserPaperService orderUserPaperService;

    @Autowired
    private WelcoFeign welcoFeign;

    //添加试卷
    @PostMapping("/addpaper")
    public void addparper(HttpServletResponse response, OrderPaper orderPaper) throws IOException {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format(date);
        orderPaper.setCreateTime(format);
        int paper = orderPaperService.insertOrderPaper(orderPaper);
        writeJSON(paper,response, "200", "添加成功");
    }

    //批量删除试卷
    @GetMapping("/deletepaper")
    public void deletequestion(HttpServletResponse response, OrderPaper orderPaper, String[] ids) throws IOException{


        writeJSON( orderPaperService.deleteOrderPaperByIds(ids),response,"200","删除成功");
    }

    //修改试卷
    @PostMapping("/updatepaper")
    public void updatequestion(HttpServletResponse response, OrderPaper orderPaper) throws IOException{
        Integer id = orderPaper.getId();
        if(id != null){
            writeJSON(orderPaperService.updateOrderPaper(orderPaper),response,"200","修改成功");
        }else {
            writeJSON(null,response,"201","输入错误");
        }
    }

//    //查询试卷列表
//    @GetMapping("/selectlist")
//    public void selectquestionlist(HttpServletResponse response, OrderPaper orderPaper) throws IOException{
//        List<OrderPaper> orderPapers = orderPaperService.selectOrderPaperList(orderPaper);
//        for (OrderPaper paper : orderPapers) {
//            Integer classId = paper.getClassId();
//            if(classId != 0){
//                if(!orderPapers.isEmpty()){
//                    writeJSON(orderPapers,response,"200","查询成功");
//                }else {
//                    writeJSON(null,response,"201","查无此班");
//                }
//                writeJSON(null,response,"201","未绑定班级");
//            }
//        }
//    }

    //查询试卷列表(未作答)   查试卷列表
    @GetMapping("/selectlist")
    public void selectquestionlist(HttpServletResponse response, OrderPaper orderPaper) throws IOException{
        List<OrderPaper> orderPapers = orderPaperService.selectOrderPaperList(orderPaper);
        Iterator<OrderPaper> it = orderPapers.iterator();
        OrderAnswer orderAnswer = new OrderAnswer();
        while(it.hasNext()){
            OrderPaper next = it.next();
            Integer paperId = next.getId();
            orderAnswer.setUserId(orderPaper.getUserId());
            orderAnswer.setPaperId(paperId);
            List<OrderAnswer> orderAnswers = orderAnswerService.selectOrderAnswerList(orderAnswer);
            if(orderAnswers.size()!=0){
                it.remove();
            }
        }
        writeJSON(orderPapers,response,"200","查询成功");

    }

    //查询试卷试题详情   查试卷中的试题
    @GetMapping("/selectquestionlist")
    public void selectpaperquestionlist(HttpServletResponse response, OrderPaperQuestion orderPaperQuestion)throws IOException{

        ArrayList<Object> arrayList = new ArrayList<>();
        ArrayList<Object> arrayList1 = new ArrayList<>();
        ArrayList<Object> arrayList2 = new ArrayList<>();
        ArrayList<Object> arrayList3 = new ArrayList<>();
        HashMap<Object, Object> map = new HashMap<>();
        List<OrderPaperQuestion> orderPaperQuestions = orderPaperQuestionService.selectOrderPaperQuestionList(orderPaperQuestion);
        for(OrderPaperQuestion orderPaperQuestion1 : orderPaperQuestions){
            Integer questionId = orderPaperQuestion1.getQuestionId();
            OrderQuestion orderQuestion = orderQuestionService.selectOrderQuestionById(questionId);
            String questionType = orderQuestion.getQuestionType();
            if("1".equals(questionType)){
                arrayList.add(orderQuestion);
            }
            if("2".equals(questionType)){
                arrayList1.add(orderQuestion);
            }
            if("3".equals(questionType)){
                arrayList2.add(orderQuestion);
            }
            if("4".equals(questionType)){
                arrayList3.add(orderQuestion);
            }
            map.put("danxuan",arrayList);
            map.put("panduan",arrayList1);
            map.put("duoxuan",arrayList2);
            map.put("jianda",arrayList3);


        }
        writeJSON(map,response,"200","查询成功");
    }

    //答题
    @PostMapping("/answers")
    public void answer(HttpServletResponse response,String json)throws IOException{

        List<OrderAnswer> orderAnswers = JSON.parseArray(json, OrderAnswer.class);

        //删除上一次该试卷的答案（多个记录）
        for (OrderAnswer orderAnswer : orderAnswers) {
            Integer paperId = orderAnswer.getPaperId();
            Integer userId = orderAnswer.getUserId();

            OrderAnswer orderAnswer1 = new OrderAnswer();
            orderAnswer1.setUserId(userId);
            orderAnswer1.setPaperId(paperId);

            //查询该答题者是否答过该套试卷
            List<OrderAnswer> orderAnswers1 = orderAnswerService.selectOrderAnswerList4(orderAnswer1);
            if(orderAnswers1 != null){
                for (OrderAnswer answer : orderAnswers1) {
                    //根据试题ID和试卷id删除记录
                    Integer questionId = answer.getQuestionId();
                    Integer paperId1 = answer.getPaperId();
                    orderAnswerService.deleteOrderAnswerById3(questionId,paperId1);
                }
            }else{
               break;
            }
            break;
        }

        //添加学生答案
        for (OrderAnswer orderAnswer : orderAnswers) {
            //2021/3/20添加正确答案
            Integer questionId = orderAnswer.getQuestionId();
            OrderQuestion orderQuestion = orderQuestionService.selectOrderQuestionById(questionId);
            String stAnswer = orderQuestion.getStAnswer();
            orderAnswer.setStanswer(stAnswer);
            //2021/3/20添加正确答案

            orderAnswer.setCreateTime(new Date());
            orderAnswerService.insertOrderAnswer(orderAnswer);
        }

        //判断试卷答题列表有没有该答题人同一套试卷（只有一条记录）
        for (OrderAnswer orderAnswer : orderAnswers) {

            Integer paperId = orderAnswer.getPaperId();
            Integer userId = orderAnswer.getUserId();
            OrderUserPaper orderUserPaper = orderUserPaperService.SelectOrderUserPaper(paperId,userId);
            if(orderUserPaper != null){
                orderUserPaperService.delete(paperId,userId);
            }else{
                break;
            }
            break;
        }
        //添加该答题者该套试卷最新记录
        for (OrderAnswer orderAnswer : orderAnswers) {
            Integer paperId = orderAnswer.getPaperId();
            Integer userId = orderAnswer.getUserId();
            OrderUserPaper orderUserPaper = new OrderUserPaper();
            orderUserPaper.setPaperId(paperId);
            orderUserPaper.setUserId(userId.toString());

            TStudent selectstudent = welcoFeign.selectstudent(userId);
            if(selectstudent!=null){
                String studentSex = selectstudent.getStudentSex();
                String studentName = selectstudent.getStudentName();
                orderUserPaper.setUserName(studentName);
                orderUserPaper.setStudentSex(studentSex);
                orderUserPaperService.InsertOrderPaper(orderUserPaper);
                break;
            }else{
                break;
            }

        }

        //系统评分
        //2021/3/20
        for (OrderAnswer orderAnswer : orderAnswers) {
            Integer paperId = orderAnswer.getPaperId();
            OrderPaper orderPaper = orderPaperService.selectOrderPaperById(paperId);
            //得到该套试卷各种题型相应的分数，
            String singleScore = orderPaper.getSingleScore();
            String judgmentScore = orderPaper.getJudgmentScore();
            String manyScore = orderPaper.getManyScore();
            //是否为系统评分
            String level = orderPaper.getLevel();
            if(level.equals("2")){
                //学生答案
                String answer1 = orderAnswer.getAnswer();
                //正确答案
                String stanswer = orderAnswer.getStanswer();

                Integer questionId = orderAnswer.getQuestionId();
                Integer paperId1 = orderAnswer.getPaperId();
                Integer userId = orderAnswer.getUserId();
                Integer type = orderAnswer.getType();
                //单选
                if(type.equals(1)){
                    if(answer1.equals(stanswer)){
                        //若相等，则填入该题相应的分数
                        OrderAnswer orderAnswer1 = new OrderAnswer();
                        orderAnswer1.setQuestionId(questionId);
                        orderAnswer1.setPaperId(paperId1);
                        orderAnswer1.setUserId(userId);
                        orderAnswer1.setScore(Integer.parseInt(singleScore));
                        orderAnswerService.updateOrderAnswer1(orderAnswer1);
                    }else{
                        OrderAnswer orderAnswer1 = new OrderAnswer();
                        orderAnswer1.setQuestionId(questionId);
                        orderAnswer1.setPaperId(paperId1);
                        orderAnswer1.setUserId(userId);
                        orderAnswer1.setScore(0);
                        orderAnswerService.updateOrderAnswer1(orderAnswer1);
                    }
                }
                //判断
                if(type.equals(2)){
                    if(answer1.equals(stanswer)) {
                        //若相等，则填入该题相应的分数
                        OrderAnswer orderAnswer1 = new OrderAnswer();
                        orderAnswer1.setQuestionId(questionId);
                        orderAnswer1.setPaperId(paperId1);
                        orderAnswer1.setUserId(userId);
                        orderAnswer1.setScore(Integer.parseInt(judgmentScore));
                        orderAnswerService.updateOrderAnswer1(orderAnswer1);
                    }else{
                        OrderAnswer orderAnswer1 = new OrderAnswer();
                        orderAnswer1.setQuestionId(questionId);
                        orderAnswer1.setPaperId(paperId1);
                        orderAnswer1.setUserId(userId);
                        orderAnswer1.setScore(0);
                        orderAnswerService.updateOrderAnswer1(orderAnswer1);
                    }
                }
                //多选
                if(type.equals(3)){
                    String[] split = answer1.split(",");
                    String[] split1 = stanswer.split(",");
                    Arrays.sort(split);
                    Arrays.sort(split1);
                    if(Arrays.equals(split,split1)){
                        //若相等，则填入该题相应的分数
                        OrderAnswer orderAnswer1 = new OrderAnswer();
                        orderAnswer1.setQuestionId(questionId);
                        orderAnswer1.setPaperId(paperId1);
                        orderAnswer1.setUserId(userId);
                        orderAnswer1.setScore(Integer.parseInt(manyScore));
                        orderAnswerService.updateOrderAnswer1(orderAnswer1);
                    }
                    else{
                        OrderAnswer orderAnswer1 = new OrderAnswer();
                        orderAnswer1.setQuestionId(questionId);
                        orderAnswer1.setPaperId(paperId1);
                        orderAnswer1.setUserId(userId);
                        orderAnswer1.setScore(0);
                        orderAnswerService.updateOrderAnswer1(orderAnswer1);
                    }
                }
            }
        }
        writeJSON(null,response,"200","添加成功");
    }

    //答题试卷列表
    @GetMapping("/AnswerPapers")
    public void AnswerPapers(HttpServletResponse response,OrderUserPaper orderUserPaper)throws IOException{
        List<OrderUserPaper> orderUserPapers = orderUserPaperService.OrderUserPaperlist1(Integer.parseInt(orderUserPaper.getUserId()));
        ArrayList<Object> list = new ArrayList<>();

        for (OrderUserPaper userPaper : orderUserPapers) {
            Integer paperId = userPaper.getPaperId();
            OrderPaper orderPaper = orderPaperService.selectOrderPaperById(paperId);
            if(orderPaper != null){
                String introduction = orderPaper.getIntroduction();
                String createTime = orderPaper.getCreateTime();
                String passscore = orderPaper.getPassscore();
                String score = userPaper.getScore();
                if(Integer.parseInt(score)<Integer.parseInt(passscore)){
                    userPaper.setPass("2");
                }else{
                    userPaper.setPass("1");
                }
                userPaper.setRtype(orderPaper.getRtype());
                userPaper.setPaperName(introduction);
                userPaper.setCreateTime(createTime);
                list.add(userPaper);
            }
        }
        writeJSON(list,response,"200","查询成功");

    }

    //成绩查询
    @GetMapping("/resultInquiry")
    public void resultInquiry(HttpServletResponse response, OrderAnswer orderAnswer) throws IOException{
        Integer paperId = orderAnswer.getPaperId();

        OrderPaperQuestion orderPaperQuestion = new OrderPaperQuestion();
        orderPaperQuestion.setPaperId(paperId);

        ArrayList<Object> danxuan = new ArrayList<>();
        ArrayList<Object> duoxuan = new ArrayList<>();
        ArrayList<Object> panduan = new ArrayList<>();
        ArrayList<Object> jianda = new ArrayList<>();

        HashMap<Object, Object> map = new HashMap<>();
        //查询试题列表
        List<OrderPaperQuestion> orderPaperQuestions = orderPaperQuestionService.selectOrderPaperQuestionList(orderPaperQuestion);
        for (OrderPaperQuestion paperQuestion : orderPaperQuestions) {
            Integer questionId = paperQuestion.getQuestionId();

            OrderQuestion orderQuestion = orderQuestionService.selectOrderQuestionById(questionId);

            OrderAnswer orderAnswer1 = orderAnswerService.selectOrderAnswerList3(paperId,orderAnswer.getUserId(),questionId);
            String answer2 = orderAnswer1.getAnswer();
            orderQuestion.setXsAnswer(answer2);
            String createTime = orderQuestion.getCreateTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                String stamp = String.valueOf(sdf.parse(createTime).getTime());
                orderQuestion.setCreateTime(stamp);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            String questionType = orderQuestion.getQuestionType();

            if("1".equals(questionType)){
                danxuan.add(orderQuestion);
            }
            if("2".equals(questionType)){
                panduan.add(orderQuestion);
            }
            if("3".equals(questionType)){
                duoxuan.add(orderQuestion);
            }
            if("4".equals(questionType)){
                jianda.add(orderQuestion);
            }

        }

        OrderPaper orderPaper = orderPaperService.selectOrderPaperById(paperId);

        BigDecimal Single = new BigDecimal(orderPaper.getSingle());//单选个数
        BigDecimal SingleScore = new BigDecimal(orderPaper.getSingleScore());//单选分数
        BigDecimal Judgment = new BigDecimal(orderPaper.getJudgment());//判断个数
        BigDecimal JudgmentScore = new BigDecimal(orderPaper.getJudgmentScore());//判断分数
        BigDecimal many = new BigDecimal(orderPaper.getManyScore());//多选分数
        //BigDecimal manyScore = new BigDecimal(orderPaper.getSingle());//多选个数取参取错了
        BigDecimal manyScore = new BigDecimal(orderPaper.getMany());//多选题个数
        BigDecimal answ = new BigDecimal(orderPaper.getAnsw());
        BigDecimal answSore = new BigDecimal(orderPaper.getAnswSore());//简答分数
        //单选个数*单选分数+判断个数*判断分数+多选个数*多选分数
        BigDecimal add = Single.multiply(SingleScore).add(Judgment.multiply(JudgmentScore)).add(many.multiply(manyScore)).add(answ.multiply(answSore));

        Integer userId = orderAnswer.getUserId();
        OrderUserPaper orderUserPaper = orderUserPaperService.SelectOrderUserPaper(paperId, userId);
        String score = orderUserPaper.getScore();

        map.put("danxuan",danxuan);
        map.put("panduan",panduan);
        map.put("duoxaun",duoxuan);
        map.put("jianda",jianda);
        map.put("zongfen",add);
        map.put("fenshu",score);

        writeJSON(map,response,"200","查询成功");
    }

    @GetMapping("/selectcomment")
    public void selectcomment(HttpServletResponse response, Integer paperId, Integer userId)throws IOException{
        OrderUserPaper orderUserPaper = orderUserPaperService.SelectOrderUserPaper(paperId, userId);
        writeJSON(orderUserPaper,response,"200","查询成功");
    }



}



